package com.jscloud.bigdata.flink.flinksql.functions.udaf;

import org.apache.flink.table.functions.AggregateFunction;

/**
 * 定义 UDAF function，必须继承 AggregateFunction 类，多进一出
 */
public   class AvgFunc  extends AggregateFunction<Double,AvgAccumulator> {
        @Override
        public Double getValue(AvgAccumulator avgAccumulator) {
                if(avgAccumulator.count==0){
                        return null;
                }else {
                        return avgAccumulator.sum/avgAccumulator.count;
                }
        }
        //初始化累加器
        @Override
        public AvgAccumulator createAccumulator() {
                return new AvgAccumulator();
        }
        //迭代累加
        public void accumulate(AvgAccumulator acc,Double score){
                acc.setSum(acc.sum+score);
                acc.setCount(acc.count+1);
        }
}